package com.hgz;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.hgz.util.Constant;
import com.hgz.util.OperateTime;
@SuppressWarnings("serial")
public class AdDemoServlet extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		ItemDao itemDao= new ItemDao();
		
		
		//写入db
		
		writeDb();
		
		//读取
		String dataPath = req.getRealPath("/")+"/data/" ;
		String fileName = OperateTime.getDate()+""+".txt";
		String filePath=dataPath+fileName;
		javaReaderFile(filePath);
		resp.setContentType("text/plain");
		resp.getWriter().println("Hello, world");

		List<Item> items = itemDao.getAllItem();
		for(Item itema:items){
			System.out.println(itema.getName());
		}
	}
	@SuppressWarnings("unused")
	public void writeDb(){
		ItemDao itemDao= new ItemDao();

		Document doc;
		try {
			doc = Jsoup.connect(Constant.FECTH_URL).get();
			Elements trContents  = doc.select("tr[class=formlist_tr]");
			for (Element trContent : trContents){
				System.out.println (trContent.text());
				String brName = trContent.text();
				String [] names = brName.split(" ");
				if(brName==null){
					continue;
				}
				if(names==null||names.length==0){
					continue;
				}
				for(int i=0;i< names.length;i++){

					Item item = new Item();
					item.setName(names[1]);
					item.setMinPrice(names[2]);
					item.setPrice(names[3]);
					item.setMaxPrice(names[4]);
					item.setDw(names[5]);
					item.setGg(names[6]);
					item.setDate(names[7]);
					itemDao.addItem(item);


				}
			}	

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	//java读取文件
	public void javaReaderFile(String path) throws IOException{  

		ItemDao itemDao= new ItemDao();

		File file=new File(path);
		if(!file.exists()||file.isDirectory())
			throw new FileNotFoundException();
		BufferedReader br=new BufferedReader(new FileReader(file));
		String temp=null;
		temp = br.readLine();
		while(temp!=null){
			temp = br.readLine();
			String brName = temp;
			if(brName==null){
				continue;
			}
			String [] names = brName.split(" ");
			if(names==null||names.length==0){
				continue;
			}
			for(int i=0;i< names.length;i++){

				Item item = new Item();
				item.setName(names[1]);
				item.setMinPrice(names[2]);
				item.setPrice(names[3]);
				item.setMaxPrice(names[4]);
				item.setDw(names[5]);
				item.setGg(names[6]);
				item.setDate(names[7]);
				itemDao.addItem(item);

			}

			System.out.println("itemDao读取>>>>>>"+temp);
		}

	}

}
